package com.jjiang.bbmall.seckill.scheduled;

import com.jjiang.bbmall.seckill.service.SeckillService;
import com.jjiang.common.constant.SecKillConstant;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * 秒杀商品定时上架的任务
 */
@EnableFeignClients
@Service
public class SeckillSkuScheduled {
    @Autowired
    SeckillService seckillService;

    @Autowired
    RedissonClient redissonClient;

    //    @Scheduled(cron = "0 0 3 * * ?") // 每天晚上凌晨3点执行
    @Scheduled(cron = "0 */10 * * * ?") // 测试时使用
    public void upLoadSeckillSku() {
        // 1.加上分布式锁，分布式服务器，只能有一台来执行一次
        RLock lock = redissonClient.getLock(SecKillConstant.SECKILL_UPLOAD_LOCK);
        lock.lock(10, TimeUnit.SECONDS);
        try {
            // 2.会有重复上架；需要做成幂等操作
            System.out.println("开始上架。。。");
            seckillService.upLoadSeckillSku();
        } finally {
            lock.unlock();
        }
    }
}
